//
//  StatusListModel.swift
//  ZHTQWeibo
//
//  Created by ZHTQ on 2018/9/28.
//  Copyright © 2018年 ZHTQ. All rights reserved.
//  用户主页网路数据请求 微博图片缓存

import UIKit

class StatusListModel: NSObject {
    /// 微博数据
    var statuses: [StatusViewModel]?
    
    /// 加载微博数据 statuses
    func loadStatus(isLastStatus: Bool, finished: @escaping (_ statuses: [StatusViewModel]?, _ error: Error?) -> ()) {
        
        // 获取第一条微博的idStr 没有数据的时候为0
        var sinceID = statuses?.first?.status?.idstr ?? "0"
        var maxId = "0"
        if isLastStatus {
            sinceID = "0"
            maxId = statuses?.last?.status?.idstr ?? "0"
        }
        
        
        NetworkTools.sharedInstance.loadStatusData(since_id: sinceID, max_id: maxId) { (arrarObj, error) in
            
            if error != nil {
                ZHLog("数据请求错误")
                
//                self.refreshControl?.endRefreshing()
//                self.reminedStatusCount(count: 0)
                return
            }
            guard let dict = arrarObj as? [String: Any] else {
                
                return
            }
            guard let statusArray = dict["statuses"] as? [[String: Any]] else {
                
                return
            }
            
            var statuses = [StatusViewModel]()
            
            for status in statusArray {
                let st = Status(dict: status)
                let stVM = StatusViewModel(status: st)
                statuses.append(stVM)
                
            }
            
            if sinceID != "0" {
                self.statuses = statuses + self.statuses!
            } else if maxId != "0" {
                self.statuses = self.statuses! + statuses
            } else {
                self.statuses = statuses
            }
            
            // 缓存所有微博图片
            self.cachedImages(viewModels: statuses, finished: finished)
            
            
        }
    }
    
    /// 缓存所有微博图片
    private func cachedImages(viewModels: [StatusViewModel], finished: @escaping (_ statuses: [StatusViewModel]?, _ error: Error?) -> ()) {
        // 创建一个dispatchGroup
        let group = DispatchGroup()
        
        for viewModel in viewModels{
            guard let urls = viewModel.thumbnail_urls else {
                continue
            }
            
            for url in urls {
                
                // 下载操作加入组
                group.enter()
                
                SDWebImageManager.shared().loadImage(with: url, options: SDWebImageOptions(rawValue: 0), progress: nil) { (image, _, error, _, _, _) in
                    
                    // 下载操作完成 移除组
                    group.leave()
                }
            }
        }
        
        group.notify(queue: DispatchQueue.main) {
            
//            self.tableView.reloadData()
//
//
//            // 取消下拉刷新
//            self.refreshControl?.endRefreshing()
//
//            // 显示下拉数据条数的动画
//            self.reminedStatusCount(count: viewModels.count)
            finished(viewModels, nil)
        }
    }
}
